import React, { Component } from 'react';
import {
	StyleSheet, Text, View, TouchableOpacity,
	PixelRatio, Image, ScrollView, FlatList, BackHandler, Alert, Platform, TextInput, Dimensions, Animated
} from "react-native";
import { API, API_GENERATE } from '../../../config/api';
import { GLOBAL } from '../../../config/global';
import StorageHelper from '../../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../../config/storage';
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common.js';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { ScrollTabView } from '../../../component/ScrollTabView';
import HTTP from '../../../utils/http';
import Permission from '../../../utils/permission';
import { NavigationEvents } from 'react-navigation';
import { GET_PAGE } from '../../../config/definition';
import { RangTime } from '../../../component/common/RangTime.js';
import { ORDER_TYPE, commonStatusTabArr, longTypeTabArr, longStatusTabArr, NEW_OIL_ORDER_TYPE } from '../../order/_common/service';
import { DashLine } from '../../../components/common/DashLine';
import Swipeable from 'react-native-swipeable';
import ToastUtil from '../../../utils/toast';
import { OrderCommon } from '../_common/common';
import { CURRENCY } from '../../../utils/helper';
import moment from 'moment';
import { NewAccount } from '../../../components/common/newAccount';
import { SlideSelect } from '../../../components/common/slideSelect';
// import { DashedLine } from '../info-new/_components/DashedLine';
import { PriceTypeUI } from '../../../component/ui/PriceTypeUI';

const scale = GLOBAL.SCALE;
/**
 * 虚线绘制
 */
const showImg = require('../../../imgs/order/show.png'); // 打开
const closeImg = require('../../../imgs/order/close.png'); // 打开
const longSale = require('../../../imgs/apply/purchase.png');//longSale 创建采购长约
const longPurchase = require('../../../imgs/apply/sale.png');//longPurchase 创建销售长约
const openPic = require('../../../imgs/apply/open.png');//longPurchase 创建销售长约
const closePic = require('../../../imgs/apply/close.png');//longPurchase 创建销售长约
const calendar = require('../../../imgs/calendar.png');
const searchIcon = require('../../../imgs/global/whiteSearch.png');
const arrowDownIcon = require('../../../imgs/global/down.png');
const deleteIcon = require('../../../imgs/apply/delete.png');

/*
	companyId :   企业详情页面用
	companyName  :  企业详情页面用
*/

const ZXY_STATUS_FILTER = ['RPT_DRAFT', 'RPT_AUDITING', 'RPT_AUDIT_UNPASS', 'EXECUTING'];

export class OrderListPage extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		const { pageType } = navigation.state.params || {};
		let title = pageType === 'LONG_FRAME' ? '长约框架' : '订单中心';
		let periodType = pageType === 'LONG_FRAME' ? 'L' : 'S';
		return {
			header: null,
		}
	}

	constructor(props) {
		super(props);
		console.log('列表传参数-00000000', props.navigation.state.params)
		let { typeIndex, statusIndex, status, isZXY, orderType, bizMode, pageType, companyId, companyName, choice } = props.navigation.state.params || {};
		this.state = {
			status: 'data',
			refreshIcon: false, // 下拉刷新图标
			addShow: false,
			showTimeModal: false, // 时间选择弹层
			showStatusSelect: false, // 订单状态选择弹层
			zxyStatusText: '全部',
			zxySelectIndex: 0,
			showZxyStatus: false,
			typeIndex: typeIndex || 0,  // 订单类型下标
			statusIndex: statusIndex || 0,  // 订单状态下标
			listData: [],
			permissionText: '',
			alertShow: false,
			options: [],
			choice: choice || {}
		}
		this.hideEnter = false;
		this.isLong = pageType === 'LONG_FRAME';
		this.isZXY = !!isZXY;
		this.reload = true; // 判断是整个页面刷新还是下拉刷新
		this.totalPage = 1;
		this.orderType = [];
		this.orderStatus = [];
		this.currentlyOpenSwipeable = null;
		this.pageParams = {
			pageNo: 1,
			pageSize: 10,
			beginDate: '',
			endDate: '',
			searchKey: companyName || null
		};

		this.zxyPageParams = {
			statusList: ZXY_STATUS_FILTER,
			pushStatusList: [],
			lockStatusList: []
		};
		this.longPageParams = { statusList: ['EXECUTING'] };
	}

	initTab = async () => {
		let { typeIndex } = this.state;
		if (this.isLong) {
			this.hideEnter = !Permission.check('LON007') && !Permission.check('LON013');
			let lsArr = [];
			if (Permission.check('LON002')) lsArr.push(longTypeTabArr[0]);
			if (Permission.check('LON008')) lsArr.push(longTypeTabArr[1]);
			this.orderType = lsArr;
		} else {
			this.orderType = ORDER_TYPE;
			this.orderStatus = typeIndex == 2 ? NEW_OIL_ORDER_TYPE : commonStatusTabArr;
		}

	}

	async componentWillMount() {
		await this.getSorage();
		await this.initTab();
		await this.getOrderRecord();
		await this.initPage();
	}

	//获取业务组织
	async getSorage() {
		const userInfoJson = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
		const userInfo = JSON.parse(userInfoJson);
		this.setState({
			options: userInfo.corpInfoTOs || [],
			choice: this.state.choice.corpId ? this.state.choice : userInfo.corpInfoTOs[0]
		})
	}

	initPage = async () => {
		if (!this.hasPermission()) {
			this.setState({
				status: 'empty',
				permissionText: '暂无权限',
				listData: []
			})
			return
		};
		this.setState({
			status: this.reload ? 'loading' : 'data',
			refreshIcon: !this.reload && this.pageParams.pageNo == '1'
		})
		this.currentlyOpenSwipeable && this.currentlyOpenSwipeable.recenter();
		let api = this.isZXY ? API.GET_NEW_OIL_ORDER_LIST : (this.isLong ? API.GET_LONG_ORDER_LIST : API.GET_ORDER_LIST);
		let res = await HTTP.POST(API_GENERATE(api), this.getRequestParams());
		await this.getOrderRecord();
		if (res) {
			this.totalPage = res.totalPage;
			res = this.getRequireParams(res);

			// 加图标
			res.rows && res.rows.map((item) => {
				let { isAgency, bizMode, periodType, isFuture, longOrderId, isQhXhXsBiz } = item;

				item.tCode = this._getTCode(isAgency, bizMode, periodType, isFuture, longOrderId, isQhXhXsBiz)
				return item;
			})

			this.setState({
				status: res.rows.length > 0 ? 'data' : 'empty',
				listData: this.pageParams.pageNo == '1' ? res.rows : this.state.listData.concat(res.rows),
				refreshIcon: false
			})
		} else {
			this.setState({
				refreshIcon: false,
				status: 'error'
			})
		}
	}

	hasPermission = () => {
		let { typeIndex, statusIndex } = this.state;
		let hasPermission;
		let typePermission = '';
		let statusPermission = '';
		typePermission = this.orderType[typeIndex].permission || '';
		if (this.isZXY) statusPermission = this.orderStatus[statusIndex].permission || '';
		hasPermission = Permission.check(typePermission) && Permission.check(statusPermission);
		return hasPermission
	}

	// 返回值数据补充
	getRequireParams = (res) => {
		if (res.rows && res.rows.length > 0) {
			res.rows.forEach(item => {
				item.showItem = false;
				item.boxHeight = new Animated.Value(138 * scale);
				item.openHeight = 0;
				if (this.isZXY) item.orderItemList = item.zxyOrderItemList;
				if (item.orderItemList && item.orderItemList.length > 0) {
					item.openHeight = 69 * item.orderItemList.length
				} else {
					item.orderItemList = []
				}
			})
		}
		return res
	}

	// 获取请求参数
	getRequestParams = () => {
		let { typeIndex, statusIndex, choice } = this.state;
		let requestParams = {};
		let ZXYParams = {};
		let longParams = {};
		let orderParams = {};
		this.statusItem = this.orderStatus[statusIndex];
		if (this.isZXY) {
			this.pageParams.searchCode = this.pageParams.searchKey;
			ZXYParams = { ...this.statusItem.requestParams, ...this.zxyPageParams };
		} else if (this.isLong) {
			longParams = { ...this.longPageParams };
		} else {
			orderParams.statusList = this.statusItem.statusList
		}
		requestParams = { corpId: choice.corpId, ...this.pageParams, ...orderParams, ...this.orderType[typeIndex].requestParams, ...ZXYParams, ...longParams };
		if (this.isZXY) {
			requestParams.beginDate = requestParams.beginDate ? moment(new Date(requestParams.beginDate)).format('YYYY/MM/DD') : '';
			requestParams.endDate = requestParams.endDate ? moment(new Date(requestParams.endDate)).format('YYYY/MM/DD') : '';
		} else {
			requestParams.beginDate = requestParams.beginDate ? moment(new Date(requestParams.beginDate)).format('YYYY-MM-DD') : '';
			requestParams.endDate = requestParams.endDate ? moment(new Date(requestParams.endDate)).format('YYYY-MM-DD') : '';
		}
		return requestParams
	}

	// 获取中新油订单数量
	getOrderRecord = async () => {
		if (this.isLong) return false;
		if (this.isZXY) {
			let res = await HTTP.POST(API_GENERATE(API.GET_NEW_OIL_ORDER_RECORD), this.getRequestParams());
			if (res) {
				this.orderStatus[0].count = res.purchaseOrders || 0;
				this.orderStatus[1].count = res.saleOrders || 0;
				this.orderStatus[2].count = res.oppoOrders || 0;
			}
		} else {  //获取普通订单数量
			let res = await HTTP.POST(API_GENERATE(API.GET_ORDER_LIST_TOL), this.getRequestParams());
			if (res) {
				this.orderStatus[0].count = res.draftCnt || 0;
				this.orderStatus[1].count = res.auditCnt || 0;
				this.orderStatus[2].count = res.executingCnt || 0;
				this.orderStatus[3].count = res.completedCnt || 0;
				this.orderStatus[4].count = res.abandonedCnt || 0;
			}
		}
	}

	// 长约框架创建入口
	goCreate = (sendData) => {
		const { navigate } = this.props.navigation;
		navigate('OrderBaseInfoPage', sendData);
	}

	// 重新加载
	reloadPage = () => {
		this.pageParams.pageNo = 1;
		this.reload = true;
		this.initPage();
	}

	// 下拉刷新
	refresh = () => {
		this.pageParams.pageNo = 1;
		this.reload = false;
		this.initPage();
	}

	// 加载更多
	loadMore = () => {
		if (this.totalPage > this.pageParams.pageNo) {
			this.pageParams.pageNo++;
			this.reload = false;
			this.initPage();
		}
	}

	// 刷新
	onErrorRefresh = () => {
		this.pageParams.pageNo = 1;
		this.reload = true;
		this.initPage();
	}

	// 切换订单类型
	changeOrderType = (item, index) => {
		let { typeIndex } = this.state;
		let lastType = this.isZXY;
		this.pageParams.beginDate = '';
		this.pageParams.endDate = '';
		//this.pageParams.searchKey = '';
		if (typeIndex != index) {
			this.isZXY = index == 2;
			this.orderStatus = this.isZXY ? NEW_OIL_ORDER_TYPE : this.isLong ? [] : commonStatusTabArr;
			this.setState({
				statusIndex: this.isZXY == !lastType ? 0 : this.state.statusIndex, // 中新油和普通订单切换时，需要将订单状态初始化
				typeIndex: index
			}, () => {
				this.reloadPage();
			})
		} else {
			this.reloadPage();
		}
	}

	_renderOrderType = () => {
		let { typeIndex } = this.state;
		return (
			<View style={styles.orderTypeWrap}>
				{
					!(GLOBAL.ORDER_KEY == 'OrderStack') ? <TouchableOpacity style={styles.goBackWrap} onPress={() => { this.props.navigation.goBack() }} activeOpacity={0.5}>
						<Image source={require('../../../imgs/goBack.png')} />
					</TouchableOpacity> : null
				}
				{
					this.orderType.map((item, index) => {
						return (
							<TouchableOpacity key={index} activeOpacity={.6} style={[{ marginRight: 28 * scale }, typeIndex == index ? styles.selectedType : '']} onPress={() => this.changeOrderType(item, index)}>
								<Text style={[styles.commonType, typeIndex == index ? { opacity: 1 } : '']}>{item.tabName}</Text>
							</TouchableOpacity>
						)
					})
				}
			</View>
		)
	}

	// 切换订单状态
	changeOrderStatus = (item, index) => {
		let { statusIndex } = this.state;
		if (statusIndex != index) {
			//this.zxyPageParams.statusList = ZXY_STATUS_FILTER;
			this.setState({
				statusIndex: index,
				//zxySelectIndex: 0,
				//zxyStatusText: '全部',
			}, () => {
				this.reloadPage();
			})
		} else {
			this.reloadPage();
		}
	}

	_renderOrderStatus = () => {
		let { statusIndex } = this.state;
		return (
			<View style={styles.orderStatusWrap}>
				{
					this.orderStatus && this.orderStatus.map((item, index) => {
						return (
							<TouchableOpacity key={index} activeOpacity={.6} style={statusIndex == index ? styles.selectedStatus : ''} onPress={() => this.changeOrderStatus(item, index)}>
								<Text style={[styles.commonStatus, statusIndex == index ? { opacity: 1 } : '']}>{item.text}</Text>
								<Text style={[styles.statusCount, styles.commonStatus, statusIndex == index ? { opacity: 1 } : '']}>{Permission.check(item.permission || '') ? item.count : 0}</Text>
							</TouchableOpacity>
						)
					})
				}
			</View>
		)
	}

	_renderFilterWrap = () => {
		let { beginDate, endDate } = this.pageParams;
		return (
			<View style={styles.filterWrap}>
				<TouchableOpacity activeOpacity={.8} style={styles.dateWrap} onPress={() => {
					this.setState({
						showTimeModal: true,
						showStatusSelect: false,
					})
				}}>
					<View style={styles.dateImgWrap}>
						<Image source={calendar} style={{ width: 17 * scale, height: 14 * scale }} />
					</View>
					<View style={{ flexDirection: 'column', justifyContent: 'center', alignItems: 'center' }}>
						<Text style={styles.dateText}>{beginDate || '开始时间'}</Text>
						<Text style={styles.dateLine}></Text>
						<Text style={styles.dateText}>{endDate || '结束时间'}</Text>
					</View>
				</TouchableOpacity>

				<View>
					<Image source={searchIcon} style={styles.searchIcon} />
					<TextInput
						ref="enterpriseInput"
						style={styles.searchInput}
						underlineColorAndroid='transparent'
						placeholder={"请输入查询内容"}
						placeholderTextColor="rgba(255, 255, 255, .8)"
						maxLength={30}
						returnKeyType={'search'}
						defaultValue={this.pageParams.searchKey}
						onChangeText={(txt) => { this.pageParams.searchKey = txt; }}
						onSubmitEditing={() => { this.reloadPage(); }}
					/>
				</View>
			</View>
		)
	}

	// 选择时间
	_resultCall = (resultData) => {
		this.pageParams.beginDate = resultData.startTime || '';
		this.pageParams.endDate = resultData.endTime || '';
		this.setState({
			showTimeModal: false
		}, () => {
			this.reloadPage()
		})
	}

	// 中新油状态切换
	changeZxyStatus = (res) => {
		if (res) {
			this.zxyPageParams.pushStatusList = [];
			this.zxyPageParams.lockStatusList = [];
			if (res.item.statusList) {
				this.zxyPageParams.statusList = res.item.statusList;
				this.zxyPageParams.pushStatusList = res.item.pushStatusList;
				this.zxyPageParams.lockStatusList = res.item.lockStatusList;
			} else {
				this.zxyPageParams.statusList = ZXY_STATUS_FILTER;
			}
			this.setState({
				showZxyStatus: false,
				zxySelectIndex: res.index,
				zxyStatusText: res.item.title,
			}, () => {
				this.reloadPage();
			})
		}
	}

	// 商品展开和隐藏
	toggleProduct = (index, currentHeight, openHeight) => {
		let { listData } = this.state;
		listData[index].showItem = !listData[index].showItem;
		Animated.spring(currentHeight, {
			duration: 300,
			toValue: listData[index].showItem ? openHeight * scale : 138 * scale,
		}).start();
		this.setState({ listData })
	}

	// 删除草稿确认
	deleteOrderConfirm = (orderId) => {
		Alert.alert('提示', '您确定要删除本单吗?', [
			{
				text: '取消',
			}, {
				text: '确定',
				onPress: () => {
					this.removeOrder(orderId);
				}
			}
		]);
	}

	// 删除草稿
	async removeOrder(orderId) {
		const deleteInfo = await HTTP.POST(API_GENERATE(API.ORDER_DELETE), { orderId });
		if (deleteInfo) {
			ToastUtil.showSuccess('删除成功').then(() => this.reloadPage())
		}
	}

	// 滑动删除打开
	onOpenDelete(event, gestureState, swipeable) {
		if (this.currentlyOpenSwipeable && this.currentlyOpenSwipeable !== swipeable) {
			this.currentlyOpenSwipeable.recenter();
		}
		this.currentlyOpenSwipeable = swipeable;
	}

	// 滑动删除关闭
	onCloseDelete(event, gestureState, swipeable) {
		this.currentlyOpenSwipeable = null;
	}

	// 跳详情页面
	goDetail = (data) => {
		console.log('data', data)
		const { typeIndex, statusIndex, choice } = this.state;
		if (this.isLong) {//长约框架
			this.props.navigation.navigate('LongOrderDetailPage', { pramasData: data, ...this.orderType[typeIndex].requestParams, choice })
		} else if (typeIndex == 2) { //中新油
			let pageName = '';
			if (data.status == 'RPT_DRAFT' || data.status == 'RPT_AUDIT_UNPASS') {
				pageName = 'SinoNewOrderBaseInfoPage'
			} else {
				pageName = 'SinoNewOrderDetailPage'
			}
			this.props.navigation.navigate(pageName, {
				paramsData: {
					orderId: data.orderId,
					orderType: statusIndex == 1 ? 'S' : 'P',
					...this.orderType[typeIndex].requestParams,
					bizMode: data.bizMode,
					status: data.status,
					statusName: data.statusName,
				},
				choice
			})
		} else {
			if (statusIndex == 0) { //草稿去新增
				let pageUrl = data.bidId ? 'OrderDetailsPage' : 'orderBasePage'
				this.props.navigation.navigate(pageUrl, {
					orderId: data.orderId,
					type: 'edit',
					bidId: data.bidId,
					...this.orderType[typeIndex].requestParams,
					tCode: data.tCode,
					bizMode: data.bizMode,
					choice
				})
			} else {
				this.props.navigation.navigate('OrderDetailsPage', { ...this.orderType[typeIndex].requestParams, orderId: data.orderId, tCode: data.tCode, choice })
			}
		}
	}

	// code 获取
	_getTCode = (isAgency, bizMode, periodType, isFuture, longOrderId, isQhXhXsBiz) => {
		let tCode;
		if (isAgency == 1) {//代理
			tCode = 'A'
		} else if (bizMode == 1) {//闭口
			tCode = 'C'
		} else if (periodType == 'L') {//长约框架
			tCode = 'L'
		} else if (isFuture == 1) {//远期
			tCode = 'F'
		} else if (isQhXhXsBiz == 'Y') {//泉化销售
			tCode = 'QH'
		} else if (longOrderId) {//执行
			tCode = 'E'
		} else {//现货
			tCode = 'S'
		}
		return tCode;
	}

	_renderListItem = (data) => {
		let { status, orderId } = data.item;
		let { typeIndex } = this.state;
		return (
			<View style={{ paddingLeft: 12 * scale, paddingRight: 12 * scale }}>
				{
					(typeIndex != 2 && status == 'RPT_DRAFT') ? (
						<Swipeable
							rightButtons={[
								<TouchableOpacity onPress={() => { this.deleteOrderConfirm(orderId) }}>
									<View style={[{
										justifyContent: 'center',
										height: '100%'
									}]}>
										<Image source={deleteIcon} style={styles.deleteImg}></Image>
									</View>
								</TouchableOpacity>
							]
							}
							onSwipeStart={() => this.setState({ isSwiping: true })}
							onSwipeRelease={() => this.setState({ isSwiping: false })}
							onRightButtonsOpenRelease={this.onOpenDelete.bind(this)}
							onRightButtonsCloseRelease={this.onCloseDelete.bind(this)}
							disableLeftSwipe={false}
						>
							{this._renderListItemContent(data)}
						</Swipeable>
					) : this._renderListItemContent(data)
				}
			</View>
		)
	}
	_renderListItemContent = (data) => {
		let itemData = data.item;
		let { statusIndex, listData } = this.state;
		let isZXYBackToBack = this.isZXY && statusIndex == 2;
		let unit = CURRENCY.getUnit(itemData.currency).text;
		let unitSymbol = CURRENCY.getUnit(itemData.currency).label;
		return (
			<View style={[{ paddingBottom: 5 * scale }, data.index == listData.length - 1 ? { paddingBottom: 12 * scale } : '']}>
				{
					isZXYBackToBack ? (
						<View style={{ flexDirection: 'row', justifyContent: 'flex-start', marginBottom: 4 * scale }}>
							<Image source={OrderCommon.iconData.purchaseImg} style={{ marginRight: 8 * scale, marginTop: -3 * scale, }} />
							<Text numberOfLines={1} style={{ color: '#272727' }}>{itemData.oppoCompanyName}</Text>
						</View>
					) : null
				}
				<View style={{ flexDirection: 'row', justifyContent: 'space-between', }}>
					<View style={{ flexDirection: 'row', flex: 1 }}>
						{isZXYBackToBack ? <Image source={OrderCommon.iconData.saleImg} style={{ marginRight: 8 * scale, marginTop: -3 * scale, }} /> : null}
						<Text numberOfLines={1} style={{ color: '#272727' }}>{itemData.companyName}</Text>
					</View>
					<Text style={{ color: '#272727', fontSize: 13 * scale, opacity: .6 }}>{itemData.createTime}</Text>
				</View>
				<TouchableOpacity activeOpacity={.6} style={styles.listItem} onPress={() => { this.goDetail(itemData) }}>
					<View style={styles.itemHeader}>
						<View style={{ flexDirection: 'row', alignItems: 'center' }}>
							<Text style={{ color: '#272727', fontSize: 13 * scale }}>{itemData.orderId}</Text>

							{this.isZXY && this.state.typeIndex == 2 ? <Image source={OrderCommon.iconData.newImg} style={styles.orderTypeImg} /> : null}
							{itemData.tCode == 'QH' ? <Image source={OrderCommon.iconData.quanHuaImg} style={styles.orderTypeImg} /> : null}
							<Image source={itemData.tradeType == 'I' ? OrderCommon.iconData.innerImg : OrderCommon.iconData.outerImg} style={styles.orderTypeImg} />
							{this.isLong ? null : <Image source={OrderCommon._showIcon(itemData.tCode)} style={styles.orderTypeImg} />}
							{this.isLong && this.state.typeIndex && itemData.isQhXhXsBiz == 'Y' ? <Image source={OrderCommon.iconData.quanHuaImg} style={styles.orderTypeImg} /> : null}
							{!this.isZXY && itemData.status && itemData.status == 'RPT_CANCELING' ? <Image source={OrderCommon.iconData.withdrawImg} style={styles.orderTypeImg} /> : null}
							{itemData.tCode == 'QH' && itemData.orderCancelStatus == '1' ? <Image source={OrderCommon.iconData.scrapImg} style={styles.orderTypeImg} /> : null}
							{itemData.bidId ? <View style={styles.costTableRed}><Text style={{ fontSize: 11 * scale, color: '#FFF' }}>壹化</Text></View> : null}
						</View>
						<Text style={[{ color: '#FA4516', fontSize: 13 * scale }]}>{this.isLong ? '进行中' : itemData.statusName}</Text>
					</View>
					<Animated.View style={[styles.itemBody, itemData.orderItemList.length > 2 ? { height: itemData.boxHeight, overflow: 'hidden' } : '']}>
						{
							itemData.orderItemList.map((item, index) => {
								return (
									<View key={index}>
										<View style={styles.productItem}>
											{
												isZXYBackToBack ? this._renderZXYBackToBack(item, itemData.currency) : this._renderOrderProductItem(item, itemData.currency)
											}
											{/* <DashedLine /> */}
										</View>
									</View>
								)
							})
						}
					</Animated.View>
					<View style={styles.itemFooter}>
						<Text style={{ fontSize: 13 * scale, color: '#272727' }}>共：{this.isZXY ? itemData.totalItemQuantity || '--' : (itemData.totalOrderQuantity || '--')}吨 </Text>
						{
							this.isLong ? null : (
								<View style={{ flexDirection: 'row', alignItems: 'center' }}>
									<Text style={{ fontSize: 13 * scale, color: '#272727' }}>合计：{unitSymbol}{itemData.totalOrderAmt || '--'}{unit}</Text>
									{/* <Text style={{ fontSize: 13 * scale, color: '#272727' }}>{unitSymbol}</Text>
									<Text style={{ fontSize: 13 * scale }}>{itemData.totalOrderAmt || '--'}</Text>
									<Text style={{ fontSize: 13 * scale, color: '#272727' }}>{unit}</Text> */}
								</View>
							)
						}
					</View>

				</TouchableOpacity>
				{
					itemData.orderItemList && itemData.orderItemList.length > 2 ? (
						<TouchableOpacity activeOpacity={1} style={styles.toggleImg} onPress={() => this.toggleProduct(data.index, itemData.boxHeight, itemData.openHeight)}>
							<Image source={itemData.showItem ? closeImg : showImg} />
						</TouchableOpacity>
					) : null
				}
			</View >
		)
	}
	_renderOrderProductItem = (item, currency) => {
		let unit = CURRENCY.getUnit(currency).text;
		let unitSymbol = CURRENCY.getUnit(currency).label;
		let itemCommonTextLabelStyle = { textAlign: 'left', opacity: .6 };
		let itemCommonTextValueStyle = { textAlign: 'left', fontSize: 14 * scale };
		let itemCommonTextViewStyle = { flex: 1, flexDirection: 'column', justifyContent: 'center', alignItems: 'flex-start', marginBottom: 12 };
		if (this.isLong) {
			return (
				<View>
					<View style={{ flexDirection: 'row', justifyContent: 'center', alignItems: 'flex-start' }}>
						<Text style={{ flex: 1, textAlign: 'left', fontWeight: 'bold', fontSize: 14 * scale }} numberOfLines={3}>{item.goodsName || '--'}</Text>
						<View style={itemCommonTextViewStyle}>
							<Text style={[styles.itemCommonText, itemCommonTextLabelStyle]} numberOfLines={1}>长约总量({item.uomName || '吨'})</Text>
							<Text style={[styles.itemCommonText, itemCommonTextValueStyle]} numberOfLines={1}>{item.quantity || '--'}</Text>
						</View>
						<View style={itemCommonTextViewStyle}>
							<Text style={[styles.itemCommonText, itemCommonTextLabelStyle]} numberOfLines={1}>剩余量({item.uomName || '吨'})</Text>
							<Text style={[styles.itemCommonText, itemCommonTextValueStyle]} numberOfLines={1}>{item.executableQuantity || '--'}</Text>
						</View>
					</View>
				</View >
			)
		} else {
			return (
				<View>
					<View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
						<View style={{ flexDirection: 'row', alignItems: 'center', flex: 1 }}>
							<Text style={{ textAlign: 'left', fontWeight: 'bold', fontSize: 14 * scale }}>{item.goodsName || '--'}</Text>
							{item.priceType ? <PriceTypeUI data={{ priceType: item.priceType }} /> : null}
						</View>
						<Text style={[{ flex: 1, textAlign: 'right' }]} numberOfLines={1}>
							<Text style={[styles.itemCommonText, { fontSize: 11 * scale }]}>{unitSymbol}</Text>
							<Text style={[styles.itemCommonText, { fontSize: 14 * scale }]}>{this.isZXY ? item.nakedPrice || '--' : item.price || '--'}</Text>
							<Text style={[styles.itemCommonText]}>{unit}/吨</Text>
						</Text>
					</View>
					<View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-end' }}>
						<Text style={[styles.itemCommonText, { opacity: .6 }]}>数量: {item.quantity || '--'}吨</Text>
					</View>
				</View>
			)
		}
	}
	_renderZXYBackToBack = (item, currency) => {
		let unit = CURRENCY.getUnit(currency).text;
		let unitSymbol = CURRENCY.getUnit(currency).label;
		return (
			<View>
				<View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', height: '50%' }}>
					<Text style={{ flex: 1, textAlign: 'left', fontWeight: 'bold', fontSize: 14 * scale }} numberOfLines={1}>{item.goodsName || '--'}</Text>
					<Text style={[styles.itemCommonText, { flex: 1, textAlign: 'center', opacity: .6 }]} numberOfLines={1}>数量：{item.quantity || '--'}吨</Text>
					<View style={{ flexDirection: 'row', alignItems: 'center', flex: 1 }}>
						<Text style={[{ flex: 1, textAlign: 'right' }]} numberOfLines={1}>
							<Text style={{ color: '#F5A623', fontSize: 13 * scale, fontWeight: 'bold' }}>采 </Text>
							<Text style={[styles.itemCommonText, { fontSize: 11 * scale }]}>{unitSymbol}</Text>
							<Text style={[styles.itemCommonText, { fontSize: 14 * scale }]}>{item.nakedPrice || '--'}</Text>
							<Text style={[styles.itemCommonText]}>{unit}/吨</Text>
						</Text>
					</View>
				</View>
				<View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-end', height: '50%' }}>
					<Text style={{ flex: 1, textAlign: 'right' }} numberOfLines={1}>
						<Text style={{ color: '#417505', fontSize: 13 * scale, fontWeight: 'bold' }}>销 </Text>
						<Text style={[styles.itemCommonText, { fontSize: 11 * scale }]}>{unitSymbol}</Text>
						<Text style={[styles.itemCommonText, { fontSize: 14 * scale }]}>{item.nakedSalePrice || '--'}</Text>
						<Text style={[styles.itemCommonText]}>{unit}/吨</Text>
					</Text>
				</View>
			</View>
		)
	}
	_renderZXYFilter = () => {
		let { zxyStatusText } = this.state;
		return (
			<View style={{ paddingTop: 16 * scale, paddingLeft: 12 * scale }}>
				<TouchableOpacity style={{ flexDirection: 'row', justifyContent: 'center', alignItems: 'center', width: 104 * scale, height: 28 * scale, backgroundColor: 'rgba(235,235,235,.5)', borderRadius: 2 * scale }} activeOpacity={.6} onPress={() => { this.setState({ showZxyStatus: !this.state.showZxyStatus }) }}>
					<View style={{ flexDirection: 'row', justifyContent: 'center', alignItems: 'center' }}>
						<Text style={{ color: '#272727', opacity: .8, fontSize: 12 * scale }}>{zxyStatusText}</Text>
						<Image style={{ marginLeft: 4 * scale, opacity: .8 }} source={arrowDownIcon} />
					</View>
				</TouchableOpacity>
			</View>
		)
	}

	render() {
		let { status, addShow, listData, refreshIcon, showTimeModal, showZxyStatus, zxySelectIndex, permissionText, alertShow, choice, options } = this.state;
		return (
			<View style={styles.container}>
				<NavigationEvents onWillFocus={async ({ action }) => {
					await this.getSorage();
					this.reloadPage();
					if (GLOBAL.ORDER_KEY == 'OrderStack') {
						this.setState({ ls: true })
					}
				}}
				/>
				<View style={styles.headerWrap}>
					{/* 订单类型切换 */}
					{this._renderOrderType()}
					{/* 业务组织选择 */}
					{options.length > 1 ? <NewAccount fn={(val) => { this.setState({ alertShow: val }) }} choice={choice.corpName || ''} /> : null}
					{/* 过滤条件 */}
					{this._renderFilterWrap()}
					{/* 订单状态切换 */}
					{this._renderOrderStatus()}
				</View>

				{/* 中新油状态过滤 */}
				{
					this.isZXY ? this._renderZXYFilter() : null
				}

				{/* 列表 */}
				{
					status == 'data' ? (<View style={{ flex: 1, paddingBottom: 20 * scale, paddingTop: 16 * scale }}>
						<FlatList
							data={listData}
							style={styles.listWrap}
							renderItem={this._renderListItem}
							refreshing={refreshIcon}
							onRefresh={() => { this.refresh() }}
							onEndReachedThreshold={0.1}
							onEndReached={() => { this.loadMore() }}
						/>
					</View>) : null
				}

				{/* 创建长约框架的入口 */}
				{this.hideEnter || !this.isLong ? null :
					(<View style={{ bottom: 40 * scale, right: 10 * scale, position: 'absolute' }}>
						{addShow ? <View>
							{Permission.check('LON007') ?
								<TouchableOpacity onPress={() => {
									this.goCreate({
										orderType: 'P',
										periodType: 'L',
										tCode: 'L',
									})
								}}>
									<Image source={longSale} style={{ marginBottom: 8 * scale, width: 47 * scale, height: 47 * scale }}></Image>
								</TouchableOpacity> : null
							}
							{Permission.check('LON013') ?
								<TouchableOpacity onPress={() => {
									this.goCreate({
										orderType: 'S',
										periodType: 'L',
										tCode: 'L',
									})
								}}>
									<Image source={longPurchase} style={{ marginBottom: 8 * scale, width: 47 * scale, height: 47 * scale }} ></Image>
								</TouchableOpacity> : null
							}
						</View> : null}
						<TouchableOpacity activeOpacity={1} onPress={() => {
							this.setState({
								addShow: !this.state.addShow
							})
						}}>
							<Image source={addShow ? closePic : openPic} style={{ width: 47 * scale, height: 47 * scale }}></Image>
						</TouchableOpacity>
					</View>)
				}

				{
					status != 'data' ? (<PageStatusIndex status={status} emptyText={permissionText || '暂无记录'} onErrorPress={this.onErrorRefresh} />) : null
				}

				{
					showTimeModal ? <RangTime isVisible={true} markedDates={null} startTime={this.pageParams.beginDate} endTime={this.pageParams.endDate} closeCall={() => { this.setState({ showTimeModal: false }) }} resultCall={this._resultCall} /> : null
				}

				{showZxyStatus ? (<Common data={OrderCommon.ZXY_STATUS_LIST} itemFn={this.changeZxyStatus} imgIndex={zxySelectIndex} allClick={() => { this.setState({ showZxyStatus: !this.state.showZxyStatus }) }} styleOut={{ paddingTop: 150 * scale }} type="selectModal" />) : null}

				<SlideSelect alertShow={alertShow} options={options}
					select={(val) => {
						this.setState({ choice: val || options[0], alertShow: false }, () => {
							this.reloadPage();
						})
					}}
					unselect={() => {
						this.setState({ alertShow: false })
					}} />
			</View>
		)
	}

}

const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.bgGray,
	},
	headerWrap: {
		backgroundColor: style.color.themeColor,
		paddingTop: Platform.OS === 'ios' ? 34 * scale : 10 * scale,
		paddingLeft: 22 * scale,
		paddingRight: 22 * scale,
	},
	goBackWrap: {
		height: '100%',
		width: 28 * scale,
		flexDirection: 'row',
		justifyContent: 'flex-start',
		alignItems: 'center',
	},
	orderTypeWrap: {
		flexDirection: 'row',
		alignItems: 'center',
		marginTop: 16 * scale,
	},
	commonType: {
		fontSize: 16 * scale,
		color: '#fff',
		opacity: .65,
		marginBottom: 8 * scale,
	},
	selectedType: {
		borderBottomWidth: 1,
		borderBottomColor: '#fff',
		borderStyle: 'solid',
	},
	orderStatusWrap: {
		marginTop: 23 * scale,
		flexDirection: 'row',
		justifyContent: 'space-between',
		alignItems: 'center',
	},
	commonStatus: {
		fontSize: 14 * scale,
		color: '#fff',
		opacity: .65,
	},
	statusCount: {
		textAlign: 'center',
		paddingTop: 6 * scale,
		paddingBottom: 8 * scale,
	},
	filterWrap: {
		marginTop: 5 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-between',
		position: 'relative',
	},
	dateWrap: {
		width: 115 * scale,
		height: 36 * scale,
		paddingLeft: 36 * scale,
		borderRadius: 18 * scale,
		backgroundColor: 'rgba(255 ,255 , 255, .18)',
		flexDirection: 'row',
		justifyContent: 'center',
		paddingRight: 14 * scale,
	},
	dateImgWrap: {
		width: 36 * scale,
		height: 36 * scale,
		borderRadius: 18 * scale,
		backgroundColor: 'rgba(255, 255, 255, .08)',
		position: 'absolute',
		top: 0,
		left: 0,
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
	},
	dateText: {
		fontSize: 10 * scale,
		color: '#fff',
		opacity: .8,
		textAlign: 'center'
	},
	dateLine: {
		width: 7 * scale,
		height: 1 * scale,
		backgroundColor: 'rgba(255, 255, 255, .36)',
		marginTop: 3 * scale,
		marginBottom: 3 * scale,
	},
	searchInput: {
		height: 36 * scale,
		width: 210 * scale,
		paddingLeft: 42 * scale,
		paddingRight: 12 * scale,
		backgroundColor: 'rgba(255, 255, 255, .18)',
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
		paddingVertical: 0,
		position: 'relative',
		borderRadius: 18 * scale,
		color: '#fff',
	},
	searchIcon: {
		width: 20 * scale,
		height: 22 * scale,
		position: 'absolute',
		left: 12 * scale,
		top: 8 * scale,
		zIndex: 9,
		opacity: 0.8,
	},
	listWrap: {
		flex: 1,
	},
	listItem: {
		backgroundColor: '#fff',
		borderRadius: 4 * scale,
		marginTop: 7 * scale,
		paddingLeft: 12 * scale,
		paddingRight: 12 * scale,
		paddingBottom: 12 * scale,
		paddingTop: 12 * scale,
	},
	itemHeader: {
		flexDirection: 'row',
		justifyContent: 'space-between',
		alignItems: 'center',
	},
	orderTypeImg: {
		marginLeft: 5 * scale,
		height: 16 * scale,
		width: 16 * scale
	},
	itemCommonText: {
		fontSize: 13 * scale,
		color: '#272727',
		paddingBottom: 6 * scale,
		paddingTop: 4 * scale
	},
	itemFooter: {
		height: 20 * scale,
		flexDirection: 'row',
		justifyContent: 'flex-end',
		alignItems: 'center',
		marginTop: 10 * scale
	},
	itemBody: {
		position: 'relative',
		overflow: 'hidden',
		backgroundColor: '#fff'
	},
	productItem: {
		paddingTop: 12 * scale,
		paddingBottom: 12 * scale,
		height: 68 * scale,
		borderBottomWidth: 1 / PixelRatio.get(),
		borderBottomColor: '#EFEFEF',
		borderStyle: 'solid',
	},
	toggleImg: {
		height: 30 * scale,
		width: '100%',
		flexDirection: 'row',
		justifyContent: 'center',
		marginBottom: 15 * scale,
	},
	deleteImg: {
		width: 50 * scale,
		height: 50 * scale,
		marginLeft: 20 * scale,
		marginRight: 20 * scale,
	},
	costTableRed: {
		borderRadius: 2 * scale,
		paddingHorizontal: 4 * scale,
		paddingVertical: 2 * scale,
		marginLeft: 5 * scale,
		backgroundColor: '#E02020'
	}
})